package com.xxxx.rpc.service.impl;



import com.xxxx.rpc.mapper.GoodsCategoryMapper;
import com.xxxx.rpc.pojo.GoodsCategory;

import com.xxxx.rpc.service.GoodsCategoryService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Service(interfaceClass = GoodsCategoryService.class)
@Component
public class GoodsCategoryServiceimpl implements GoodsCategoryService {


    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;
    /**
     * 商品分类-查询所有-分类
     */
    @Override
    public List<GoodsCategory> selectGCategoryList() {
        List<GoodsCategory> list=goodsCategoryMapper.selectByPrimaryId(null);
        System.out.println(list);
        List<GoodsCategory> listout=new ArrayList<>();

/*        for (GoodsCategory i : list){
            if (i.getLevel()==1){
                listout.add(i);//承接数据用于返还到controller层
            }
        }

        return listout;
        */
        int num=0;
        for (GoodsCategory i : list) {//遍历每一个元素

            List<GoodsCategory> list01 = null;//初始化
            if (i.getParentId()==0){//通过判断得出（0）首层没有父节点的一层


                list.set(num,part(list,i,list01));//更新list中的数据利用封装过的方法part

                listout.add(list.get(num));//承接数据用于返还到controller层

                num++;//计数器
            }


        }

        return listout;

    }


    public GoodsCategory part(List<GoodsCategory> list , GoodsCategory i ,List<GoodsCategory> list01 ){

        if (i.getLevel()<3){//判断该元素是否是一个父级节点（拥有下级）


            list01 = new ArrayList<>();//初始化
            for (GoodsCategory j : list) {//当i拥有下级再次遍历将对应下级放入容器

                if (j.getParentId().equals(i.getId())) {//找到子类
                    j=part(list,j,list01);//递归此方法
                    list01.add(j);
                }
            }
            i.setChildren(list01);

            return i;
        }
        return i;
    }



}
